<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2017/8/21
 * Time: 14:46
 */

namespace app\controllers;


use app\core\lib\Controller;
use app\models\Product;
use app\models\ProductCate;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;

class ProductController extends Controller
{

    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\HttpCache',
//                'only' => ['index'],
                'etagSeed' => function($action, $params){
                    return serialize(date('Y-m-d'));
                }
            ]
        ];
    }

    public function actionIndex(){
        $cid = Yii::$app->request->get('cid', 0);
        $productCate = ProductCate::find()->asArray()->all();
        $productCate = array_merge([['id'=>0, 'name'=>'全部']], $productCate);
        if ($cid != 0 ) $where['cid'] = $cid;
        $where['status'] = 1;
        $query = Product::find()->where($where);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
//                'defaultPageSize' => 1,
                'pageSize' => 6
            ]
        ]);

        return $this->render('index',[
            'dataProvider' => $dataProvider,
            'productCate' => $productCate,
        ]);
    }

    public function actionView($id){
        $model = $this->findModel($id);
        return $this->render('view',[
            'model' => $model
        ]);
    }

    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}